import React from 'react'
import { observer, inject } from 'mobx-react'
import { observable, computed } from 'mobx'
import { Table } from 'antd'
import moment from 'moment'

import { Filter, PageLoading, PreviewImage } from '../../compontents'

import st from './index.scss'

function getSchemaAttrForTable(schema, rule) {
  const { show_rule, attriutes } = schema

  const mathAttr = (key) => {
    const attr = attriutes[key]
    const row = {
      title: attr['alias'],
      key: attr['name'],
      dataIndex: attr['name'],
      ellipsis: true
    }
    switch (attr.type) {
      case 'datetime':
        row.render = (value) => moment(value).format('YYYY-MM-DD HH:mm:ss')
        break
      case 'image_array':
        row.render = (value) => (
          <div>
            {value &&
              value.map((src, idx) => (
                <PreviewImage key={idx} height="50px" width="50px" src={src} />
              ))}
          </div>
        )
        break
      case 'indexof':
        row.render = (value, rec) => {
          if ('alternatives' in attr) {
            for (let item of attr.alternatives) {
              if (value == item.value) {
                value = item.name
              }
            }
          }
          return value
        }
    }
    return row
  }

  if (!show_rule || !show_rule[rule]) {
    return Object.keys(attriutes).map((key) => {
      return mathAttr(key)
    })
  }
  return Object.keys(attriutes)
    .map((key) => {
      return mathAttr(key)
    })
    .filter((obj) => show_rule[rule].indexOf(obj.key) !== -1)
}

@inject('schema', 'utils', 'user', 'define')
@observer
export default class DataIndex extends React.Component {
  @observable name = null
  @observable list = []
  @observable loading = false
  @observable total = 0
  @observable params_array = []
  @computed get params() {
    const params = {
      page: this.page,
      per_page: this.per_page
    }

    if (this.params_array) {
      this.params_array.forEach((param) => {
        if ('value' in param) {
          params[param.name] = param.value
        }
      })
    }

    return params
  }
  page = 1
  per_page = 10

  componentDidMount() {
    this.init()
  }

  componentDidUpdate() {
    this.init()
  }

  init() {
    const { utils, schema } = this.props
    const params = utils.getMatchParams(this.props)

    if (
      'name' in params &&
      typeof params.name === 'string' &&
      schema[params.name] &&
      this.name !== params.name
    ) {
      this.page = 1
      this.per_page = 10
      this.params_array = []
      this.name = params.name
    }
  }

  getColumns() {
    const { schema } = this.props

    return getSchemaAttrForTable(schema[this.name], 'index')
  }

  async onSearch(params) {
    this.params_array = params
    this.getList()
  }

  async getList() {
    const { user, schema, utils } = this.props
    const url = utils.getSchemaApi(schema[this.name], 'index')

    this.loading = true
    const res = await user.get({
      url,
      params: this.params
    })

    if (res.status === 200) {
      this.list = res.data
      this.total = res.headers['x-pagination-total-count'] || this.total
    } else {
      this.list = []
      this.total = 0
    }
    this.loading = false
  }

  async pageChange(page, page_sie) {
    this.page = page
    this.per_page = page_sie
    await this.getList()
  }

  async pageSizeChange(page_now, page_size) {
    const page = Math.round((this.page * this.per_page) / page_size)
    this.page = page
    this.per_page = page_size
    await this.getList()
  }

  render() {
    const { schema } = this.props

    if (!this.name) {
      return <PageLoading />
    }

    return (
      <div key={this.name}>
        <Filter
          schema={schema[this.name]}
          onSearch={this.onSearch.bind(this)}
        />
        <div className={st['table']}>
          <Table
            rowKey="id"
            loading={this.loading}
            dataSource={this.list.slice()}
            columns={this.getColumns()}
            pagination={{
              current: this.page,
              pageSize: this.per_page,
              total: this.total,
              responsive: true,
              onChange: this.pageChange.bind(this),
              onShowSizeChange: this.pageSizeChange.bind(this)
            }}
          />
        </div>
      </div>
    )
  }
}
